package com.eden.manage.service;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.eden.manage.dto.PageComDto;
import com.eden.manage.dto.UserInfoDto;
import com.eden.manage.dto.agent.AgentDto;
import com.eden.manage.mapper.EdenPlatAgentInfoMapper;
import com.eden.manage.model.EdenPlatAgentInfo;
import com.eden.manage.req.query.AgentQuery;
import com.eden.manage.utils.WebUserUtils;
import com.eden.manage.utils.mapstruct.AgentStructUtils;
import eden.api.common.enums.UserTypeEnum;
import eden.api.common.model.PageQuery;
import eden.api.common.utils.ErrorEnums;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class AgentService {

    private final EdenPlatAgentInfoMapper edenPlatAgentInfoMapper;

    public PageComDto<AgentDto> pageList(AgentQuery agentQuery){
        dealDataAuth(agentQuery);
        PageComDto<AgentDto> agentPageDto = new PageComDto<>();
        int count = edenPlatAgentInfoMapper.countByPage(agentQuery);
        if(count > 0){
            List<AgentDto> agentDtos = edenPlatAgentInfoMapper.selectPageList(agentQuery);
            dealParentName(agentDtos);
            agentPageDto.setList(agentDtos);
        }
        agentPageDto.setCount(count);
        return agentPageDto;
    }

    private void dealParentName(List<AgentDto> agentDtos) {
        if(CollectionUtils.isEmpty(agentDtos)){
            return;
        }
        List<Long> ids = agentDtos.stream().map(AgentDto::getParentId).collect(Collectors.toList());
        Map<Long, String> agentMap = edenPlatAgentInfoMapper.selectListByIds(ids).stream().collect(Collectors.toMap(EdenPlatAgentInfo::getId, EdenPlatAgentInfo::getAgentName, (it1, it2) -> it1));
        agentDtos.forEach(it -> it.setParentName(agentMap.get(it.getParentId())));

    }

    private void dealDataAuth(PageQuery pageQuery) {
        UserInfoDto userInfo = WebUserUtils.getUserInfo();
        if(UserTypeEnum.ADMIN.getCode().equals(userInfo.getType())){
            // 管理员不需要进行条件判断
            return;
        }
        if(UserTypeEnum.PLAT.getCode().equals(userInfo.getType())){
            StringBuilder sb = new StringBuilder();
            sb.append("pa.plat_id=")
                    .append(userInfo.getPlatId());
            pageQuery.setDataAuth(sb.toString());
        }else{
            StringBuilder sb = new StringBuilder();
            sb.append("pa.plat_id=")
                    .append(userInfo.getPlatId())
                    .append(" and ")
                    .append(" pa.parent_id = ")
                    .append(userInfo.getAgentId());
            pageQuery.setDataAuth(sb.toString());
        }
    }


    @Transactional(rollbackFor = Exception.class)
    public void openAgent(Long agentId){
        edenPlatAgentInfoMapper.openAgent(agentId);
    }

    @Transactional(rollbackFor = Exception.class)
    public void frozenAgent(Long agentId){
        edenPlatAgentInfoMapper.frozenAgent(agentId);
    }
    @Transactional(rollbackFor = Exception.class)
    public void freeAgent(Long agentId){
        edenPlatAgentInfoMapper.freeAgent(agentId);
    }
    @Transactional(rollbackFor = Exception.class)
    public void editAgent(AgentDto agentDto){
        UserInfoDto userInfo = WebUserUtils.getUserInfo();
        if(userInfo.getType().equals(UserTypeEnum.ADMIN.getCode())){
            throw new IllegalArgumentException(ErrorEnums.ADMIN_NOT_OPT.name());
        }
        if(agentDto.getId() != null && agentDto.getId() > 0){
            edenPlatAgentInfoMapper.updateAgent(agentDto);
        }else{
            LocalDateTime now = LocalDateTime.now();
            // 新增
            EdenPlatAgentInfo edenPlatAgentInfo = AgentStructUtils.INSTANCE.convertDtoToDB(agentDto);
            edenPlatAgentInfo.setCreateTime(now);
            edenPlatAgentInfo.setUpdateTime(now);
            edenPlatAgentInfo.setId(IdWorker.getId());
            edenPlatAgentInfo.setIsDelete(0);
            edenPlatAgentInfo.setStatus(0);
            edenPlatAgentInfo.setPlatId(userInfo.getPlatId());
            if(userInfo.getType().equals(UserTypeEnum.PLAT.getCode())){
                edenPlatAgentInfo.setLevel(1);
                edenPlatAgentInfo.setParentId(0L);
                edenPlatAgentInfo.setRoutingPath(String.valueOf(edenPlatAgentInfo.getId()));
            }else if (userInfo.getType().equals(UserTypeEnum.AGENT.getCode())){
                AgentDto userAgent = userInfo.getAgentDto();
                edenPlatAgentInfo.setLevel(userAgent.getLevel()+1);
                edenPlatAgentInfo.setParentId(userAgent.getId());
                edenPlatAgentInfo.setRoutingPath(userAgent.getRoutingPath()+"|"+ edenPlatAgentInfo.getId());
            }
            edenPlatAgentInfoMapper.insert(edenPlatAgentInfo);
        }
    }

}
